use std::collections::HashMap;
use std::sync::Mutex;
use tauri::WebviewWindow;

#[derive(Debug)]
pub struct WebviewSession {
    pub webview_window: WebviewWindow,
    pub data_directory: String,
    pub user_agent: String,
    pub created_at: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Default)]
pub struct WebviewManager {
    sessions: Mutex<HashMap<String, WebviewSession>>,
}

impl WebviewManager {
    pub fn new() -> Self {
        Self {
            sessions: Mutex::new(HashMap::new()),
        }
    }
    
    pub fn create_session(
        &self,
        tab_id: String,
        url: String,
        user_agent: String,
        data_directory: String,
        app_handle: &tauri::AppHandle,
    ) -> Result<(), String> {
        // 在Tauri 2.0中，创建新的WebView窗口
        // 注意：这需要根据Tauri 2.0的具体API进行调整
        
        // 创建WebView窗口配置
        let webview_window = tauri::WebviewWindowBuilder::new(
            app_handle,
            &tab_id,
            tauri::WebviewUrl::External(url.parse().map_err(|e| format!("Invalid URL: {}", e))?),
        )
        .title("隔离标签页")
        .user_agent(&user_agent)
        .build()
        .map_err(|e| format!("Failed to create webview: {}", e))?;
        
        let session = WebviewSession {
            webview_window,
            data_directory,
            user_agent,
            created_at: chrono::Utc::now(),
        };
        
        self.sessions.lock().unwrap().insert(tab_id, session);
        
        Ok(())
    }
    
    pub fn close_session(&self, tab_id: &str) -> Result<(), String> {
        let mut sessions = self.sessions.lock().unwrap();
        
        if let Some(session) = sessions.remove(tab_id) {
            // 关闭WebView窗口
            // 在Tauri 2.0中，WebviewWindow有close方法
            // session.webview_window.close().map_err(|e| format!("Failed to close webview: {}", e))?;
            
            // 清理数据目录
            if std::path::Path::new(&session.data_directory).exists() {
                std::fs::remove_dir_all(&session.data_directory)
                    .map_err(|e| format!("Failed to clean data directory: {}", e))?;
            }
        }
        
        Ok(())
    }
    
    pub fn navigate_session(&self, _tab_id: &str, _url: String) -> Result<(), String> {
        let sessions = self.sessions.lock().unwrap();
        
        if let Some(_session) = sessions.get(_tab_id) {
            // 导航到新的URL
            // 在Tauri 2.0中，WebviewWindow有navigate方法
            // session.webview_window.navigate(url).map_err(|e| format!("Failed to navigate: {}", e))?;
        }
        
        Ok(())
    }
    
    pub fn get_session(&self, tab_id: &str) -> Option<WebviewSession> {
        let sessions = self.sessions.lock().unwrap();
        sessions.get(tab_id).cloned()
    }
    
    pub fn get_all_sessions(&self) -> Vec<String> {
        let sessions = self.sessions.lock().unwrap();
        sessions.keys().cloned().collect()
    }
}

// 为WebviewSession实现Clone trait
impl Clone for WebviewSession {
    fn clone(&self) -> Self {
        // 注意：WebviewWindow不能直接克隆，这里返回一个简化版本
        // 在实际使用中，应该避免克隆WebviewSession
        Self {
            webview_window: self.webview_window.clone(), // 如果WebviewWindow实现了Clone
            data_directory: self.data_directory.clone(),
            user_agent: self.user_agent.clone(),
            created_at: self.created_at,
        }
    }
}